<?php
/**
 * @Author: Ron Chen
 * @Date:   2017-07-18 21:19:46
 * @Last Modified by:   Ron Chen
 * @Last Modified time: 2018-01-17 21:56:07
 */

namespace app\services;

use Yii;
use yii\web\Response;
use app\models\InsurancePolicy;

/**
* 工具相关服务相关服务
*/
class ToolServices
{
	/**
	 * 根据当前生日计算年龄
	 */
	public static function birthday($birthday){ 
	    $age = strtotime($birthday); 
	    if($age === false){ 
	        return 0; 
	    } 
	    list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age)); 
	    $now = strtotime("now"); 
	    list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now)); 
	    $age = $y2 - $y1; 
	    if((int)($m2.$d2) < (int)($m1.$d1)) 
	        $age -= 1; 
	    return $age; 
	}

	/**
     * 加密
     */
    public static function encrypt($data,$key='funfind_zxcvbnm'){
        $key    =   md5($key);  
        $x      =   0;  
        $len    =   strlen($data);  
        $l      =   strlen($key); 
        $char   = '';
        $str    = '';
        for ($i = 0; $i < $len; $i++)  
        {  
            if ($x == $l)   
            {  
                $x = 0;  
            }  
            $char .= $key{$x};  
            $x++;  
        }  
        for ($i = 0; $i < $len; $i++)  
        {  
            $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);  
        }  
        return base64_encode($str);  
    }

    /**
     * 解密
     */
    public static function decrypt($data, $key='funfind_zxcvbnm')
    {
        $key = md5($key);  
        $x = 0;  
        $data = base64_decode($data);  
        $len = strlen($data);  
        $l = strlen($key);  
        $char   = '';
        $str    = '';
        for ($i = 0; $i < $len; $i++)  
        {  
            if ($x == $l)   
            {  
                $x = 0;  
            }  
            $char .= substr($key, $x, 1);  
            $x++;  
        }  
        for ($i = 0; $i < $len; $i++)  
        {  
            if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))  
            {  
                $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));  
            }  
            else  
            {  
                $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));  
            }  
        }  
        return $str; 
    }
}